package com.buka.filter;

import com.alibaba.nacos.client.naming.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class AuthFilter implements GlobalFilter, Ordered {
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //请求
        ServerHttpRequest request = exchange.getRequest();
        //响应
        ServerHttpResponse response = exchange.getResponse();
        try {
            //判断是否是登录接口
            String path = request.getURI().getPath();
            if (path.contains("/auth/login")) {
                return chain.filter(exchange);
            }
            //从cookie里取jti
            String jti = request.getCookies().getFirst("uid").getValue();
            if (StringUtils.isEmpty(jti)) {
                //jti为空，拒绝访问
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
            //从redis中取出token
            String token = redisTemplate.opsForValue().get(jti).toString();
            if (StringUtils.isEmpty(token)) {
                //token为空，拒绝访问
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
            //header请求头处理增加Bearer
            String authorization = request.getHeaders().getFirst("Authorization");
            request.mutate().header("Authorization", "Bearer " + authorization);
            return chain.filter(exchange);
        } catch (Exception e) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
